<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" plain :icon="Delete" @click="allDel">批量删除</el-button>
            <el-button type="primary" :icon="CirclePlus" @click="addClass">添加</el-button>
        </div>

        <el-table class="table-mb" v-loading="loading" :data="arr_data" :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="cate_id"
            @selection-change="handleAllSelected">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="cate_id" label="分类ID" width="100"></el-table-column>
            <el-table-column prop="title" label="分类名称" min-width="180"></el-table-column>
            <el-table-column label="是否隐藏">
                <template #default="{ row }">
                    <span>{{ row.hidden == 0 ? "显示" : "隐藏" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="排序" min-width="130">
                <template #default="{ row }">
                    <el-input v-model.trim="row.order_by" clearable placeholder="请输入排序数字"
                        oninput="value=value.replace(/[^\d.]/g,'')" style="width: 100px" @change="() => inputSort(row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="240" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickEdit(row)">编辑
                    </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination background v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="pageSizeNum"
            :total="totalNums" layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-dialog v-model="dialogClass" :title="classType == 1 ? '添加分类' : '编辑分类'" width="540px" :append-to-body="true"
            :destroy-on-close="true" :close-on-click-modal="false" @close="closeAddClass">
            <el-form ref="ruleClassRef" :model="ruleClassForm" :rules="ruleCheckClass" label-width="120px">
                <el-form-item label="上级分类" prop="cate_id">
                    <el-select v-model="ruleClassForm.cate_id" placeholder="请选择上级分类" :disabled="classType == 2">
                        <el-option :label="item.title" :value="item.cate_id" v-for="(item, index) in class_options"
                            :key="index" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model.trim="ruleClassForm.name" clearable placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="是否隐藏" prop="special_status">
                    <el-switch v-model="ruleClassForm.special_status" inline-prompt :active-value="1" :inactive-value="0"
                        active-text="是" inactive-text="否" />
                </el-form-item>
                <el-form-item label="排序" prop="sort" required>
                    <el-input v-model.number="ruleClassForm.sort" clearable oninput="value=value.replace(/[^\d.]/g,'')"
                        placeholder="请输入排序数字" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitClassForm(ruleClassRef)">
                            {{ classType == 1 ? "确认添加" : "确认修改" }}
                        </el-button>
                        <el-button @click="resetClassForm(ruleClassRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <go-back />
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, onBeforeUnmount } from "vue"
import OneLoad from "@mixins/one-load"
import { Delete, CirclePlus } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getClass();
})
//清除
onBeforeUnmount(() => {
    
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pageSize.value = val
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    page.value = val
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("article/cate/index", params)
}

/**
 * 添加/编辑
 * @param {Boolean} dialogClass 添加/编辑弹窗状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} classType 弹窗类型，1是添加，2是编辑
 * @param {Array} ruleClassRef 表单规则
 * @param {Object} ruleClassForm  表单字段
 * @param {Object} ruleCheckClass  表单提示
 * @param {Function} submitClassForm 提交表单
 * @param {Function} addClass 添加分类
 * @param {Function} closeAddClass 关闭弹窗
 */
const dialogClass = ref(false)
const form_loading = ref(false)
const classType = ref(1)
const ruleClassRef = ref(null)
const ruleClassForm = reactive({
    sub_cate_id: '',
    cate_id: 0,
    name: "",
    sort: "100",
    special_status: 0, // [0:显示,1:隐藏]
})
const ruleCheckClass = reactive({
    cate_id: [{ required: true, message: "请选择上级分类", trigger: "change" }],
    name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
    sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
})
const submitClassForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                title: ruleClassForm.name,
                hidden: ruleClassForm.special_status,
                order_by: ruleClassForm.sort,
            }
            if (classType.value == 1) {
                data.parent_id = ruleClassForm.cate_id
            } else {
                data.cate_id = ruleClassForm.sub_cate_id
            }

            let url = classType.value == 1 ? "article/cate/add" : "article/cate/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogClass.value = false
                        if (classType.value == 2) {
                            getClass()
                        }
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetClassForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const addClass = () => {
    dialogClass.value = true
    classType.value = 1
}
const closeAddClass = () => {
    dialogClass.value = false
    resetClassForm(ruleClassRef.value)
}
// 编辑
const clickEdit = (row) => {
    dialogClass.value = true
    setTimeout(() => {
        ruleClassForm.name = row.title
        ruleClassForm.sort = row.order_by
        ruleClassForm.cate_id = row.parent_id
        ruleClassForm.sub_cate_id = row.cate_id
        ruleClassForm.special_status = Number(row.hidden)
        classType.value = 2
    }, 50);
}
// 删除单个
const clickDel = (row) => {
    postDel(row.cate_id)
}
// 删除多个
const ids = ref([])
const handleAllSelected = (val) => {
    ids.value = val
}
const allDel = () => {
    if (ids.value.length == 0) {
        proxy.$message({message:"请选择需要删除的数据",type:"warning"})
        return
    }
    let arrs = []
    for (let i = 0; i < ids.value.length; i++) {
        arrs.push(ids.value[i].cate_id)
    }
    postDel(arrs)
}
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("article/cate/delete", {
            cate_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => { })
}

// 排序
const inputSort = (row) => {
    proxy.$axios
        .post("article/cate/sort", {
            cate_id: row.cate_id,
            order_by: row.order_by,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => { })
}

// 获取分类
const class_options = ref([{
    cate_id: 0,
    title: '顶级分类'
}])
function getClass() {
    proxy.$axios.get('article/cate/add').then(res => {
        if (res.data.code == 0) {
            let result = res.data.data
            result.unshift({
                cate_id: 0,
                title: '顶级分类'
            })
            class_options.value = result
            getList()
        } else {
            proxy.$message({message:res.data.msg,type:"error"})
        }
    }).catch(err => { })
}
</script>
<script>
export default {
    name: "NewsClass",
}
</script>

<style lang="less" scoped></style>